package com.javaee.service.user.impl;

import com.javaee.entity.Department;
import com.javaee.entity.User;
import com.javaee.mapper.admin.UserMapper;
import com.javaee.mapper.user.UserUserMapper;
import com.javaee.service.user.AuthUserService;
import com.javaee.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.util.List;

@Service
public class AuthUserServiceImpl implements AuthUserService {
    @Autowired
    private UserUserMapper userUserMapper;
    @Autowired
    UserMapper userMapper;
    @Override
    public User login(String phone, String password) {
        User user = userUserMapper.findByPhone(phone);
        if (user != null && user.getPwd().equals(password)) {
            return user;
        }
        return null;
    }

    @Override
    public void registerPatient(String password, String name, String sex, String address, LocalDate birthday, String cno, String phone, MultipartFile doctorPhoto) {
        User user = new User();
//        user.setUsername(username);
        user.setPwd(password);
        user.setName(name);
        user.setSex(sex);
        user.setAddress(address);
        user.setBirthday(birthday);
        user.setCno(cno);
        user.setPhone(phone);
        user.setRole("user"); // 假设患者角色在数据库中存储为"user"
        // 上传头像到阿里云OSS
        String fileUrl = null;
        if (doctorPhoto != null && !doctorPhoto.isEmpty()) {
            try {
                // 尝试上传文件，并捕获可能抛出的异常
                fileUrl = AliOssUtil.uploadFile(doctorPhoto.getOriginalFilename(), doctorPhoto.getInputStream());
            } catch (Exception e) {
                // 记录异常信息，并决定如何处理异常
                e.printStackTrace();
                throw new RuntimeException("头像上传失败: " + e.getMessage());
            }
        }
        user.setTx(fileUrl);
        userUserMapper.insert(user);
    }

    @Override
    public User selectAUser(int id) {
        return userMapper.selectAUser(id);
    }

    @Override
    public int updateBalance(int id, double balance) {
        return userUserMapper.updateBalance(id,balance);
    }

    @Override
    public List<Department> selectAllDepartments() {
        return userUserMapper.selectAllDepartments();
    }
}
